<script setup>
// 使用 nextTick 确保组件渲染完成
import { ref, nextTick } from 'vue'
import ArticleSelect from './ArticleSelect.vue'
import { Plus } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import { artPublishService, artArticleInfo, artUpdateArticle } from '@/api/article.js'
import { ElMessage } from 'element-plus';
import { baseURL } from '@/utils/request.js'
import axios from 'axios';
const drawerStatus = ref(false)
const imageUrl = ref('')
const editorRef = ref()
// 默认数据
const defaultForm = {
    title: '',
    cate_id: '',
    cover_img: '', //封面图片 file对象
    state: ''
}

// 准备数据
const formModel = ref({ ...defaultForm })

const onSelectFile = (uploadfile) => {
    // console.log(uploadfile);
    // 获得路径直接在前端预览
    imageUrl.value = URL.createObjectURL(uploadfile.raw)
    formModel.value.cover_img = uploadfile.raw


}
const emit = defineEmits(['success'])
// 发布文章
const publishArticle = async (status) => {
    formModel.value.state = status

    //注意：当前接口，需要的是 formData对象
    //将普通对象转换成 formData对象
    const fd = new FormData()
    for (let key in formModel.value) {
        fd.append(key, formModel.value[key])
    }

    // 发送请求
    if (formModel.value.id) {
        // 编辑
        await artUpdateArticle(fd)
        ElMessage.success('修改成功')
        // 通知父组件，添加成功，进行数据渲染
        emit('success', 'edit')
    } else {
        // 添加
        await artPublishService(fd)
        ElMessage.success('添加成功')
        // 通知父组件，添加成功，进行数据渲染
        emit('success', 'add')
    }
    drawerStatus.value = false

}



// 组件向外暴露一个方法 open，基于open传来的参数，区分添加还是编辑
// open({}) 空对象 =》 表单无需渲染，说明是添加功能
// open({id,...}) 有数据 => 表单需要渲染， 说明是编辑功能
// open调用后，打开弹窗
const open = async (row) => {
    console.log(row);
    if (row.id) {
        // 编辑
        // 根据id发送请求获取详情
        const res = await artArticleInfo(row.id)
        console.log("res", res.data.data);
        formModel.value = res.data.data
        // 图片回显需要单独处理 拼接服务器地址
        imageUrl.value = baseURL + formModel.value.cover_img

        // 注意：提交给后台，需要的数据格式是 file对象格式
        // 需要将网络图片地址 =》 转换成file岁，存储起来
        const file = await urlToFile(imageUrl.value, formModel.value.cover_img, 'image/png')

        formModel.value.cover_img = file
        console.log("file-formModel", formModel.value);



    } else {
        // 添加
        // 初始化表单
        formModel.value = { ...defaultForm }
        // 图片上传img地址，富文本编辑器内容 ==》 需要手动重置
        imageUrl.value = ''
        // editorRef.value.setHTML('')
        await nextTick() // 等待 DOM 更新
        if (editorRef.value) {
            editorRef.value.setHTML('') // 现在可以安全调用

        }
    }
    drawerStatus.value = true
}
async function urlToFile(url, filename, mimeType) {
    try {
        // 1. 获取图片数据 (ArrayBuffer)
        const response = await axios.get(url, {
            responseType: 'arraybuffer' // 关键：指定响应格式
        });

        // 2. 将 ArrayBuffer 转为 Blob
        const blob = new Blob([response.data], { type: mimeType });

        // 3. 从 Blob 创建 File 对象
        return new File([blob], filename, { type: mimeType });
    } catch (error) {
        console.error('转换失败:', error);
        throw error;
    }
}
defineExpose({
    open
})


</script>
<template>
    <!-- 抽屉 -->
    <el-drawer v-model="drawerStatus" :title="formModel.id ? '编辑文章' : '添加文章'" size="50%">
        <el-form>
            <el-form-item label="文章标题">
                <el-input placeholder="请输入标题" v-model="formModel.title"></el-input>
            </el-form-item>
            <el-form-item label="文章分类">
                <ArticleSelect v-model="formModel.cate_id"></ArticleSelect>
            </el-form-item>
            <el-form-item label="文章封面">
                <el-upload class="avatar-uploader" :show-file-list="false" :auto-upload="false"
                    :on-change="onSelectFile">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="文章内容">
                <div class="editor">
                    <QuillEditor ref="editorRef" v-model:content="formModel.content" content-type="html" theme="snow">
                    </QuillEditor>
                </div>
            </el-form-item>
        </el-form>
        <el-form-item>
            <el-button type="primary" @click="publishArticle('已发布')">发布</el-button>
            <el-button type="info" @click="publishArticle('草稿')">草稿</el-button>
        </el-form-item>
        <!-- <template #footer>
            <el-button>发布</el-button>
            <el-button>草稿</el-button>
        </template> -->
    </el-drawer>
</template>
<style lang="scss" scoped>
.avatar-uploader {
    :deep() {
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-trandition-durantion-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;

        }
    }
}

.editor {
    width: 100%;

    :deep(.ql-editor) {
        min-height: 200px;
    }
}
</style>